import axios from 'axios'
import { useUserStore } from '@/stores/index.js'
import { ElMessage } from 'element-plus'
import router from '@/router'

const baseURL = 'http://127.0.0.1:8080'

const instance = axios.create({
  baseURL,
  timeout: 10000
})

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 携带token
    const useUser = useUserStore()
    if (useUser) {
      config.headers.Authorization = useUser.token
    }
    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    if (response.status === 200) {
      return response.data
    }

    ElMessage({
      showClose: true,
      message: response.data.message || '服务异常'
    })

    return Promise.reject(response.data)
  },
  function (error) {
    // 特殊情况：401 权限不足或token过期
    if (error.response?.status === 401) {
      router.push('/login')
    }

    ElMessage({
      showClose: true,
      message: error.response.data.message || '服务异常'
    })

    return Promise.reject(error)
  }
)

export default instance
export { baseURL }
